import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QTableView, QVBoxLayout, QWidget, QPushButton, QLabel, QLineEdit, QMessageBox
from PyQt6.QtSql import QSqlDatabase, QSqlTableModel

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("QSqlTableModel Example")
        self.setGeometry(100, 100, 800, 600)
        
        # 设置主布局
        layout = QVBoxLayout()
        container = QWidget()
        container.setLayout(layout)
        self.setCentralWidget(container)

        # 添加表格视图
        self.tableView = QTableView()
        layout.addWidget(self.tableView)

        # 初始化模型
        self.model = QSqlTableModel()
        self.tableView.setModel(self.model)

        # 连接数据库
        self.db = QSqlDatabase.addDatabase('QODBC')
        connection_string = (
            "DRIVER={MySQL ODBC 8.4 Unicode Driver};"
            "SERVER=localhost;"
            "DATABASE=student_management;"
            "USER=root;"
            "PASSWORD=936580;"
            "OPTION=3;"
        )
        if not self.db.open():
            QMessageBox.critical(None, "Database Error", f"Unable to open database: {self.db.lastError().text()}")
            return

        # 加载数据表
        self.model.setTable('employees')
        self.model.select()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())



